// components/short-video-search-result/index.ts
const app = getApp()
import { queryOtherShortVideoByPage, addShortVideoInteractive, delShortVideoInteractive } from "../../api/index";
const videoIntersectionObserver = require("../../behavior/videoIntersectionObserver")
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [videoIntersectionObserver],
  properties: {
  
  },

  /**
   * 组件的初始数据
   */
  data: {
    pageHeight: app.globalData.pageHeight,
    navBarHeight: app.globalData.navBarHeight,
    menuRight: app.globalData.menuRight,
    menuWidth: app.globalData.menuWidth,
    menuBottom: app.globalData.menuBottom,
    menuHeight: app.globalData.menuHeight,
    menuTop: app.globalData.menuTop,
    statusBarHeight: app.globalData.statusBarHeight,
    // isSearch: true,
    historyBtnText: "查看全部搜索记录",
    topic: "",
    // 搜索参数
    searchParams: {
      "Vlog_type": 0,
      "Topic": "",
      "PageOptions": {
        "PageIndex": 1,
        "PageSize": 30
      }
    },
    videoList: [],
    videoCtxList: [],
    // 工具栏
    chatAnimate: "",
    shareAnimate: "",
    likeAnimate: "",
    starAnimate: "",
    videoObserve: null as any,
    searchHis: [],
  },
  lifetimes: {
    attached() {
      const searchHis = JSON.parse(wx.getStorageSync("searchHis") || '[]')
      this.setData({
        searchHis
      })
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    focusInput() {
      // this.setData({ isSearch: true })
    },
    back() {
      this.setData({ topic: '' })
      this.triggerEvent("tapBack")
    },
    switchHistory() {
      const historyBtnText = this.data.historyBtnText;
      const isClear = historyBtnText == '清除全部搜索记录'
      this.setData({
        historyBtnText: isClear ? '' : '清除全部搜索记录'
      });
      if (isClear) {
        this.setData({
          searchHis: []
        })
        wx.setStorageSync("searchHis", JSON.stringify([]))
      }
    },
    async getVideoByTopic(type?: String) {
      this.setHis()
      const params = Object.assign({}, this.data.searchParams, { Topic: this.data.topic });
      const res = await queryOtherShortVideoByPage(params).then(res => res);
      if (type == 'search') this.setData({ videoList: res.Data.ShortVideoDtos })
      let videoList = this.data.videoList.concat(res.Data.ShortVideoDtos);
      let map = new Map();
      for (const item of videoList) {
        if (!map.has(item.Id)) {
          map.set(item.Id, item)
        }
      }
      videoList = [...map.values()]
      this.setData({ videoList })
      wx.nextTick(() => {
        this.observeVideo()
      });
    },
    confirmInput() {
      this.getVideoByTopic('search')
    },
    clearInput() {
      console.log("点击icon");
      this.setData({
        topic: ""
      })
    },
    setInput(event) {
      const { value } = event.detail;
      this.setData({
        topic: value,
        "searchParams.PageOptions.PageIndex": 1
      })
    },
    handleScrollToLower() {
      if (this.data.isLoadAllData) return
      this.setData({
        'searchParams.pageOptions.PageIndex': ++this.data.searchParams.pageOptions.PageIndex,
        isScrollToBottom: true
      })
      this.getVideoByTopic()
    },

    // 工具栏函数
    tapLike(event) {
      const { id, status } = event.currentTarget.dataset;
      let videoList = this.data.videoList;
      const index = videoList.findIndex((ele) => ele.Id == id);
      videoList[index].LikeCount = status ? videoList[index].LikeCount - 1 : videoList[index].LikeCount + 1;
      videoList[index].LikeStatus = !status;
      this.setData({ likeAnimate: !status ? "like-fill-animate" : "", videoList });
      this.handleAPI('like', !status, id)
    },
    tapChat(event) {
      const id = event.currentTarget.dataset.id;
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1];

      currentPage.setData({ activeId: id, isShowComment: true })
    },
    tapStar(event) {
      const { status, id } = event.currentTarget.dataset;
      let videoList = this.data.videoList;
      const index = videoList.findIndex((ele) => ele.Id == id);
      videoList[index].StarCount = status ? videoList[index].StarCount - 1 : videoList[index].StarCount + 1;
      videoList[index].StarStatus = !status;
      this.setData({
        starAnimate: status ? "" : "star-fill-animate",
        videoList
      });
      this.handleAPI('star', !status, id)
    },
    tapShare(event) {
      const { id } = event.currentTarget.dataset;
      let videoList = this.data.videoList;
      const index = videoList.findIndex((ele) => ele.Id == id);
      const userInfo = wx.getStorageSync("userInfo");
      const isFirstShare = !videoList[index].ForwordUsers.includes(userInfo.Id)
      if (isFirstShare) {
        videoList[index].ForwordCount = videoList[index].ForwordCount + 1;
        videoList[index].ForwordUsers.push(userInfo.Id)
        this.setData({ videoList })
        const params = {
          "OperateType": 3,
          "ShortVideoId": id,
          "Comment": ""
        }
        addShortVideoInteractive(params)
      }
    },
    handleAPI(type, status, id) {
      const typeArr = ['like', 'star']
      const params = {
        "OperateType": typeArr.indexOf(type) + 1,
        "ShortVideoId": id,
        "Comment": ""
      }
      if (status) addShortVideoInteractive(params)
      if (!status) delShortVideoInteractive(params)
    },
    onLoaded(event) {

    },
    tapPlaySwitch(event: any, videoId?: any) {
      const id = videoId ? videoId : event.currentTarget.dataset.id;
      let videoList = this.data.videoList;
      const tapIndex = videoList.findIndex(video => video.Id == id);
      videoList.forEach(element => element.isPlay = element.Id == id ? !element.isPlay : false);
      const query = this.createSelectorQuery();
      query.selectAll(".video-window").context(nodes => {
        for (let index = 0; index < nodes.length; index++) {
          const context = nodes[index].context;
          if (index == tapIndex && videoList[tapIndex].isPlay) {
            try { context.play() } catch (error) { }
          } else {
            try { context.pause() } catch (error) { }
          }
        }
      }).exec()
      this.setData({ videoList })
    },
    observeVideo() {
      if (this.data.videoObserve) this.data.videoObserve.disconnect();
      this.data.videoObserve = wx.createIntersectionObserver(this, {
        thresholds: [1],
        observeAll: true
      }).relativeToViewport().observe('.video-container', (res) => {
        if (res.intersectionRatio == 1) {
          const id = res.id.split("-")[1]
          wx.nextTick(() => {
            this.tapPlaySwitch(undefined, id)
          })
        }

      })
    },
    tapHisKeys(event) {
      const { title, type } = event.target.dataset;
      if (type == "cell") {
        this.setData({ topic: title });
        this.getVideoByTopic('search')
      } else if (type == "close") {
        let searchHis = this.data.searchHis.filter(item => item != title);
        console.log(searchHis);

        this.setData({
          searchHis
        })
        if (this.data.historyBtnText == '查看全部搜索记录') {
          this.setData({
            historyBtnText: (searchHis.length <= 3) ? '' : '查看全部搜索记录'
          })
        }
      }
    },
    setHis() {
      let searchHis = this.data.searchHis;
      !searchHis.includes(this.data.topic) && this.data.topic.trim() != '' && searchHis.push(this.data.topic);
      this.setData({
        searchHis,
        historyBtnText: (this.data.searchHis.length <= 3) ? '' : '查看全部搜索记录'
      });
      wx.setStorageSync("searchHis", JSON.stringify(searchHis))
    },
    // 修改评论条数
    editCommentCount(id) {
      let videoList = this.data.videoList;
      const tIndex = videoList.findIndex(ele => ele.Id == id)
      videoList[tIndex].CommentCount = videoList[tIndex].CommentCount + 1;
      this.setData({ videoList })
    },

    tapVideo(event) {
      const params = Object.assign({}, this.data.searchParams, { Topic: this.data.topic });
      this.triggerEvent("tapVideoCard", { id: event.target.dataset.id, params: params })
    }

  }

})

